package com.jingtao.rabbitmq.utils;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * TTL（Time-To-Live）队列工具类
 */
@Component
public class TtlQueue {

    // TTL队列交换机名称
    private static final String TTL_EXCHANGE = "ttl.exchange";
    // TTL队列路由键
    private static final String TTL_KEY = "ttl.routingkey";

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Resource
    RabbitAdmin rabbitAdmin;

    /**
     * 发送TTL队列消息
     * @param queueName 队列名称
     * @param params 消息内容
     * @param expiration 过期时间（毫秒）
     */
    public void sendTtlQueue(String queueName, Object params, Integer expiration) {
        // 创建TTL队列和交换机
        createTtlQueueAndExchange(queueName, expiration);

        // 发送消息到队列
        rabbitTemplate.convertAndSend(TTL_EXCHANGE, TTL_KEY, params);
    }

    /**
     * 创建TTL队列和交换机
     * @param queueName 队列名称
     * @param expiration 过期时间（毫秒）
     */
    private void createTtlQueueAndExchange(String queueName, Integer expiration) {
        // 创建队列
        Map<String, Object> map = new HashMap<>();
        map.put("x-message-ttl", expiration);
        Queue queue = new Queue(queueName, true, false, false, map);
        rabbitAdmin.declareQueue(queue);

        // 创建交换机
        DirectExchange directExchange = new DirectExchange(TTL_EXCHANGE, true, false);
        rabbitAdmin.declareExchange(directExchange);

        // 队列和交换机绑定
        Binding binding = BindingBuilder.bind(queue).to(directExchange).with(TTL_KEY);
        rabbitAdmin.declareBinding(binding);
    }
}
